# -*- coding: utf-8 -*-
# @Time   : 2022/5/1 15:48
# @Author : lx2035
# HELLO LX


import sys
from PyQt5 import QtWidgets,QtCore,QtGui
from fream import Ui_Form
from PyQt5.QtCore import pyqtSlot # 引入槽函数

from socket import *
import cv2
import numpy as np

# IP地址 IP_adress
# 端口选择 Port_chose
# 选定文件 btn_chose
# 开启图像 btn_open_video
# 捕获图像 btn_getpic
# 捕获视频 btn_get_video
# 信息输出 data_output

class test(QtWidgets.QWidget,Ui_Form):
    def __init__(self):
        super(test, self).__init__() # 注册初始化事件
        self.setupUi(self)
        self.setWindowTitle("demo")

        self.path = '' # 文件路径
        self.pic_index = 0 # 图片计数
        self.video_index = 0 # 视频计数
        self.video_mode = 0 # 定时器模式显示
        self.timer_camera = QtCore.QTimer() # 初始化定时器，后面图像一帧帧显示靠这个定时器
        self.timer_camera.timeout.connect(self.show_video) # 定时器连接函数


    def socked_init(self,Port,Host): # 传入端口号和目标Ip地址
        self.sock = socket(AF_INET, SOCK_DGRAM)
        self.Host = Port
        self.Port = Host
        self.sock.bind((self.Host,self.Port))
        self.sock.setblocking(0) # 设置为非阻塞模式

    def msg(self,Filepath):
        self.path = QtWidgets.QFileDialog.getExistingDirectory(None,"选取文件夹","G:/")  # 起始路径

    @pyqtSlot()
    def on_btn_chose_clicked(self): # 选择文件
        self.msg(self) # 选择完成后会自动更新文件路径
        self.data_output.append('选择的文件夹为：'+self.path)

    @pyqtSlot()
    def on_btn_open_video_clicked(self): # 开启图像
        if self.timer_camera.isActive() == False: # 没有开始统计图像
            try:
                self.socked_init(self.IP_adress.text(),int(self.Port_chose.text()))
                self.timer_camera.start(10)
                self.data_output.append('图像传输已开始！')
                self.btn_open_video.setText('关闭图像')
            except:
                self.data_output.append('请填写正确的IP地址和端口号！')
        else:
            self.timer_camera.stop()
            self.label.clear()
            self.data_output.append('图像传输已关闭！')
            self.btn_open_video.setText('开启图像')

    @pyqtSlot()
    def on_btn_getpic_clicked(self): # 捕获图像
        cv2.imwrite(str(self.path)+'/'+str(self.pic_index)+'.jpg',self.img)
        self.data_output.append('成功保存文件'+str(self.pic_index)+'.jpg')
        self.pic_index+=1
    @pyqtSlot()
    def on_btn_get_video_clicked(self): # 捕获视频
        if self.btn_get_video.text() == '捕获视频':
            self.video_mode = 1
            self.video_out = cv2.VideoWriter(str(self.path) + '/' + str(self.video_index) + '.avi',
                                                 cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 50, (640, 480))
            self.video_index += 1
            self.btn_get_video.setText('停止捕获')
        elif self.btn_get_video.text() == '停止捕获':
            self.video_out.release()
            self.video_mode = 0
            self.btn_get_video.setText('捕获视频')
        pass
    def show_video(self):
        if self.video_mode == 0:
            self.data = None
            try: #udp传输很容易出错，这里挂上一个这个还是很有必要的
                self.data, self.address = self.sock.recvfrom(921600)
                self.receive_data = np.frombuffer(self.data, dtype='uint8')
                self.img = cv2.imdecode(self.receive_data, 1)
                self.iamge = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
                showimage = QtGui.QImage(self.iamge.data, self.iamge.shape[1], self.iamge.shape[0], self.iamge.shape[1] * 3,
                                        QtGui.QImage.Format_RGB888)
                self.label.setPixmap(QtGui.QPixmap.fromImage(showimage))
            except:
                pass
        elif self.video_mode == 1:
            self.data = None
            try: #udp传输很容易出错，这里挂上一个这个还是很有必要的
                self.data, self.address = self.sock.recvfrom(921600)
                self.receive_data = np.frombuffer(self.data, dtype='uint8')
                self.img = cv2.imdecode(self.receive_data, 1)
                self.iamge = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
                self.video_out.write(self.image)
                showimage = QtGui.QImage(self.iamge.data, self.iamge.shape[1], self.iamge.shape[0], self.iamge.shape[1] * 3,
                                        QtGui.QImage.Format_RGB888)
                self.label.setPixmap(QtGui.QPixmap.fromImage(showimage))
            except:
                pass
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    calc = test()
    calc.show()
    sys.exit(app.exec_())